﻿#region

using System;

#endregion

namespace Jiubang.Communication.Common{
    public interface ICopyFrom{
        void CopyFrom(byte[] srcArray, int srcOffset, int destOffset, int length);
    }

    public struct BufferSegment : ICopyFrom{
        /// <summary>
        /// 保存数据的缓冲区
        /// </summary>
        internal byte[] array;

        /// <summary>
        /// 缓冲区偏移量
        /// </summary>
        internal int offset;

        /// <summary>
        /// 字节数据缓冲对象
        /// </summary>
        /// <param name="array">保存数据的byte数组</param>
        /// <param name="offset">数据偏移量,小于array长度</param>
        internal BufferSegment(byte[] array, int offset){
            if (array == null)
                throw new ArgumentNullException("array");
            if (offset < 0 || offset >= array.Length)
                throw new ArgumentOutOfRangeException("offset");
            this.array = array;
            this.offset = offset;
        }

        /// <summary>
        /// 实际提供给本消息的缓冲区容量，大于等于存储的数据的长度。
        /// </summary>
        internal int Count{
            get { return array.Length; }
        }

        public byte this[int index]{
            get{
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException("index", index, "必须是小于当前长度的非负整数");
                return array[index];
            }
            set{
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException("index", index, "必须是小于当前长度的非负整数");
                array[index] = value;
            }
        }

        #region ICopyFrom Members

        public void CopyFrom(byte[] srcArray, int srcOffset, int destOffset, int length){
            if (destOffset < 0)
                throw new ArgumentOutOfRangeException("destOffset", destOffset, "参数值不能少于0");
            if (destOffset + length >= Count)
                throw new ArgumentOutOfRangeException("length", length, "在起始位" + destOffset + "复制指定长度将超过缓冲区总长度" + Count);

            Buffer.BlockCopy(srcArray, srcOffset, array, destOffset, length);
        }

        #endregion

        public bool Equals(BufferSegment segment){
            if (!offset.Equals(segment.offset)) return false;
            if (array != null && segment.array != null){
                if (array.Length != segment.array.Length) return false;
                for (int i = 0; i < array.Length; i++){
                    if (array[i] != segment.array[i]) return false;
                }
                return true;
            }
            return array == segment.array;
        }
    }
}